import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Checkbox,
  FormControlLabel,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Chip,
  Grid,
  IconButton,
  Tooltip,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { safeApiCall, getAuthHeader } from 'src/utils/api';

interface AutoAccountingRule {
  id: string;
  ruleName: string;
  ruleType: string;
  isActive: boolean;
}

interface BatchActionsProps {
  rules: AutoAccountingRule[];
  onSuccess: () => void;
}

export function AutoAccountingBatchActions({ rules, onSuccess }: BatchActionsProps) {
  const [selectedRules, setSelectedRules] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');
  
  // 对话框状态
  const [batchEnableDialog, setBatchEnableDialog] = useState(false);
  const [batchDisableDialog, setBatchDisableDialog] = useState(false);
  const [batchDeleteDialog, setBatchDeleteDialog] = useState(false);

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedRules(rules.map(rule => rule.id));
    } else {
      setSelectedRules([]);
    }
  };

  // 选择单个规则
  const handleSelectRule = (ruleId: string, checked: boolean) => {
    if (checked) {
      setSelectedRules(prev => [...prev, ruleId]);
    } else {
      setSelectedRules(prev => prev.filter(id => id !== ruleId));
    }
  };

  // 批量启用规则
  const handleBatchEnable = async () => {
    if (selectedRules.length === 0) {
      setMessage('请选择要启用的规则');
      setSeverity('warning');
      return;
    }

    try {
      setLoading(true);
      const result = await safeApiCall(
        '/api/auto-accounting/rules/batch-enable',
        'PUT',
        { ruleIds: selectedRules },
        getAuthHeader()
      );
      
      if (result.success) {
        setMessage(`成功启用 ${selectedRules.length} 个规则`);
        setSeverity('success');
        setBatchEnableDialog(false);
        setSelectedRules([]);
        onSuccess();
      } else {
        setMessage(result.error || '批量启用失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error batch enabling rules:', error);
      setMessage('批量启用失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 批量禁用规则
  const handleBatchDisable = async () => {
    if (selectedRules.length === 0) {
      setMessage('请选择要禁用的规则');
      setSeverity('warning');
      return;
    }

    try {
      setLoading(true);
      const result = await safeApiCall(
        '/api/auto-accounting/rules/batch-disable',
        'PUT',
        { ruleIds: selectedRules },
        getAuthHeader()
      );
      
      if (result.success) {
        setMessage(`成功禁用 ${selectedRules.length} 个规则`);
        setSeverity('success');
        setBatchDisableDialog(false);
        setSelectedRules([]);
        onSuccess();
      } else {
        setMessage(result.error || '批量禁用失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error batch disabling rules:', error);
      setMessage('批量禁用失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除规则
  const handleBatchDelete = async () => {
    if (selectedRules.length === 0) {
      setMessage('请选择要删除的规则');
      setSeverity('warning');
      return;
    }

    try {
      setLoading(true);
      const result = await safeApiCall(
        '/api/auto-accounting/rules/batch-delete',
        'DELETE',
        { ruleIds: selectedRules },
        getAuthHeader()
      );
      
      if (result.success) {
        setMessage(`成功删除 ${selectedRules.length} 个规则`);
        setSeverity('success');
        setBatchDeleteDialog(false);
        setSelectedRules([]);
        onSuccess();
      } else {
        setMessage(result.error || '批量删除失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error batch deleting rules:', error);
      setMessage('批量删除失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  const selectedCount = selectedRules.length;
  const activeCount = rules.filter(rule => rule.isActive).length;
  const inactiveCount = rules.filter(rule => !rule.isActive).length;

  return (
    <Box>
      {message && (
        <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
          {message}
        </Alert>
      )}

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
            <Typography variant="h6">
              批量操作
            </Typography>
            <Box display="flex" gap={1}>
              <Chip 
                label={`已选择 ${selectedCount} 项`} 
                color={selectedCount > 0 ? 'primary' : 'default'} 
                size="small"
              />
              <Chip 
                label={`启用 ${activeCount}`} 
                color="success" 
                variant="outlined" 
                size="small"
              />
              <Chip 
                label={`禁用 ${inactiveCount}`} 
                color="warning" 
                variant="outlined" 
                size="small"
              />
            </Box>
          </Box>

          {/* 全选控制 */}
          <Box sx={{ mb: 2 }}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedCount === rules.length && rules.length > 0}
                  indeterminate={selectedCount > 0 && selectedCount < rules.length}
                  onChange={(e) => handleSelectAll(e.target.checked)}
                />
              }
              label="全选"
            />
          </Box>

          {/* 批量操作按钮 */}
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6} md={3}>
              <Button
                fullWidth
                variant="contained"
                color="success"
                startIcon={<Iconify icon="eva:checkmark-circle-fill" />}
                onClick={() => setBatchEnableDialog(true)}
                disabled={selectedCount === 0}
              >
                批量启用
              </Button>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Button
                fullWidth
                variant="contained"
                color="warning"
                startIcon={<Iconify icon="eva:close-circle-fill" />}
                onClick={() => setBatchDisableDialog(true)}
                disabled={selectedCount === 0}
              >
                批量禁用
              </Button>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Button
                fullWidth
                variant="contained"
                color="error"
                startIcon={<Iconify icon="eva:trash-2-fill" />}
                onClick={() => setBatchDeleteDialog(true)}
                disabled={selectedCount === 0}
              >
                批量删除
              </Button>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Button
                fullWidth
                variant="outlined"
                startIcon={<Iconify icon="eva:refresh-fill" />}
                onClick={() => setSelectedRules([])}
                disabled={selectedCount === 0}
              >
                清除选择
              </Button>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 批量启用确认对话框 */}
      <Dialog open={batchEnableDialog} onClose={() => setBatchEnableDialog(false)}>
        <DialogTitle>确认批量启用</DialogTitle>
        <DialogContent>
          <Typography>
            确定要启用选中的 {selectedCount} 个规则吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            启用的规则将按照设定的频率自动执行
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setBatchEnableDialog(false)}>取消</Button>
          <Button onClick={handleBatchEnable} color="success" variant="contained" disabled={loading}>
            确认启用
          </Button>
        </DialogActions>
      </Dialog>

      {/* 批量禁用确认对话框 */}
      <Dialog open={batchDisableDialog} onClose={() => setBatchDisableDialog(false)}>
        <DialogTitle>确认批量禁用</DialogTitle>
        <DialogContent>
          <Typography>
            确定要禁用选中的 {selectedCount} 个规则吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            禁用的规则将停止自动执行
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setBatchDisableDialog(false)}>取消</Button>
          <Button onClick={handleBatchDisable} color="warning" variant="contained" disabled={loading}>
            确认禁用
          </Button>
        </DialogActions>
      </Dialog>

      {/* 批量删除确认对话框 */}
      <Dialog open={batchDeleteDialog} onClose={() => setBatchDeleteDialog(false)}>
        <DialogTitle>确认批量删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除选中的 {selectedCount} 个规则吗？
          </Typography>
          <Typography variant="body2" color="error" sx={{ mt: 1 }}>
            ⚠️ 此操作不可撤销，删除后将无法恢复
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setBatchDeleteDialog(false)}>取消</Button>
          <Button onClick={handleBatchDelete} color="error" variant="contained" disabled={loading}>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
